/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package it.carlom.stikkyheader.core.utils;

import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.text.DecimalFormat;

/**
 * 像素转换工具类
 */
public class PxUtil {
    private static Display display;
    private static final double HARF_VALUE = 0.5D;

    /**
     * 初始化
     *
     * @param context Context
     */
    public static void initContext(Context context) {
        display = DisplayManager.getInstance().getDefaultDisplay(context).get();
    }

    /**
     * 获取屏幕宽度
     *
     * @return 屏幕宽度
     */
    public static int screenWidth() {
        return display.getAttributes().width;
    }

    /**
     * 获取屏幕高度
     *
     * @return 屏幕高度
     */
    public static int screenHeight() {
        return display.getAttributes().height;
    }

    /**
     * fp转px
     *
     * @param fp 需要转换的fp
     * @return 转换后的px
     */
    public static float fp2px(double fp) {
        double sca = display.getAttributes().scalDensity;
        return (float) (fp * sca + HARF_VALUE * (fp >= 0 ? 1 : -1));
    }

    /**
     * vp转px
     *
     * @param vp 需要转换的vp
     * @return 转换后的px
     */
    public static float vp2px(double vp) {
        double dpi = display.getAttributes().densityPixels;
        return (float) (vp * dpi + HARF_VALUE * (vp >= 0 ? 1 : -1));
    }

    /**
     * px转vp
     *
     * @param pixValue px值
     * @return vp值
     */
    public static int px2dip(double pixValue) {
        DisplayAttributes displayAttributes = display.getAttributes();
        return (int) (pixValue / (double) displayAttributes.scalDensity + HARF_VALUE);
    }


    /**
     * 格式化数字(保留一位小数)
     *
     * @param num 数字
     * @return 格式化后的字符串
     */
    public static String formatNum(int num) {
        DecimalFormat format = new DecimalFormat("0");
        return format.format(num);
    }

    /**
     * 格式化数字(保留两位小数)
     *
     * @param num 数字
     * @return 格式化后的字符串
     */
    public static String formatNum(float num) {
        if (((int) num * 1000) == (int) (num * 1000)) {
            //如果是一个整数
            return String.valueOf((int) num);
        }
        DecimalFormat format = new DecimalFormat("0.00");
        return format.format(num);
    }
}
